<?php
use think\facade\{Db, Log, Queue};

use app\api\model\Users;
use app\api\model\FinanceRecord;

// 当前时间
function curtime()
{
    return date('Y-m-d H:i:s', time());
}

// 订单号
function getOrderNumber($name = 'MY')
{
    // return 'MY-' . date('YmdHis', time()) . rand(1000, 9999);
    return $name . '-' . date('Ymd'). str_pad(mt_rand(1, 99999), 5, 0, STR_PAD_LEFT);
}

/* 同系统函数 array_column   php版本低于5.5.0 时用  */
function array_column2($input, $columnKey, $indexKey = NULL)
{
    $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
    $indexKeyIsNull    = (is_null($indexKey)) ? TRUE : FALSE;
    $indexKeyIsNumber  = (is_numeric($indexKey)) ? TRUE : FALSE;
    $result = array();

    foreach((array)$input AS $key => $row){
        if($columnKeyIsNumber){
            $tmp = array_slice($row, $columnKey, 1);
            $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
        }else{
            $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
        }
        if(!$indexKeyIsNull){
            if ($indexKeyIsNumber){
                $key = array_slice($row, $indexKey, 1);
                $key = (is_array($key) && !empty($key)) ? current($key) : NULL;
                $key = is_null($key) ? 0 : $key;
            }else{
                $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
            }
        }
        $result[$key] = $tmp;
    }
    return $result;
}

// 密码检查
function passcheck($user_pass)
{
    $num   = preg_match("/^[a-zA-Z]+$/", $user_pass);
    $word  = preg_match("/^[0-9]+$/", $user_pass);
    $check = preg_match("/^[a-zA-Z0-9]{6,12}$/", $user_pass);

    if($num || $word){
        return 2;
    }else if(!$check){
        return 0;
    }

    return 1;
}

// 检验手机号
function checkMobile($mobile)
{
    $ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/", $mobile);

    if($ismobile){
        return 1;
    }else{
        return 0;
    }
}

// 获取指定长度的随机字符串
function random($length = 6, $numeric = 0)
{
    PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
    if($numeric){
        $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
    }else{
        $hash  = '';
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
        $max   = strlen($chars) - 1;

        for($i = 0; $i < $length; $i++){
            $hash .= $chars[mt_rand(0, $max)];
        }
    }
    return $hash;
}

// 密码加密
function setPass($pass)
{
    $authcode = 'rCt52pF2cnnKNB3Hkp';
    $pass = "#>_<#" . md5(md5($authcode . $pass));
    return $pass;
}

/**
 * @desc 根据两点间的经纬度计算距离
 * @param float $lat 纬度值
 * @param float $lng 经度值
 */
function getDistance($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6371000; //近似地球半径 单位 米

    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;

    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;

    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;

    $distance = $calculatedDistance / 1000;

    if($distance < 10){
        $rs = round($distance, 2);
    }else if($distance > 1000){
        $rs = '1000';
    }else{
        $rs = round($distance);
    }

    return $rs . 'km';
}

// 时间差计算
function datetime($time)
{
    $cha = time() - $time;
    $iz = floor($cha / 60);
    $hz = floor($iz / 60);
    $dz = floor($hz / 24);

    /* 秒 */
    $s = $cha % 60;

    /* 分 */
    $i = floor($iz % 60);

    /* 时 */
    $h = floor($hz / 24);

    /* 天 */
    if($cha < 60){
        return $cha . '秒前';
    }else if($iz < 60){
        return $iz . '分钟前';
    }else if($hz < 24){
        return $hz . '小时' . $i . '分钟前';
    }else if($dz < 30){
        return $dz . '天前';
    }else{
        return date("Y-m-d", $time);
    }
}

// 时长格式化
function getSeconds($cha, $type = 0)
{
    $iz = floor($cha / 60);
    $hz = floor($iz / 60);
    $dz = floor($hz / 24);

    /* 秒 */
    $s = $cha % 60;

    /* 分 */
    $i = floor($iz % 60);

    /* 时 */
    $h = floor($hz / 24);

    /* 天 */
    if($type == 1){
        if($s < 10){
            $s = '0' . $s;
        }

        if($i < 10){
            $i = '0' . $i;
        }

        if($h < 10){
            $h = '0' . $h;
        }

        if($hz < 10){
            $hz = '0' . $hz;
        }

        return $hz . ':' . $i . ':' . $s;
    }

    if($cha < 60){
        return $cha . '秒';
    }else if($iz < 60){
        return $iz . '分钟' . $s . '秒';
    }else if($hz < 24){
        return $hz . '小时' . $i . '分钟' . $s . '秒';
    }else if($dz < 30){
        return $dz . '天' . $h . '小时' . $i . '分钟' . $s . '秒';
    }
}

// 数字格式化
function NumberFormat($num)
{
    if($num < 10000){

    }else if($num < 1000000){
        $num = round($num / 10000, 2) . '万';
    }else if($num < 100000000){
        $num = round($num / 10000, 1) . '万';
    }else if($num < 10000000000){
        $num = round($num / 100000000, 2) . '亿';
    }else{
        $num = round($num / 100000000, 1) . '亿';
    }

    return $num;
}

// 距离格式化
function distanceFormat($distance)
{
    if($distance < 1000){
        return $distance . '米';
    }else{
        if(floor($distance / 10) < 10){
            return number_format($distance / 10, 1);  //保留一位小数，会四舍五入
        }else{
            return ">10千米";
        }
    }
}

/**
 * 获取N个月前的日期
 * @param string  $time 目标日期
 * @param int     $i 月数
 */
function lastMonthTime($time, $i){
    $time = strtotime($time);
    $lastMonth = date('n', strtotime("-" . $i . " month", strtotime("first day of 0 month", $time)));
    $nowMonth = date('n', strtotime("-" . $i . " month", $time));

    if($lastMonth != $nowMonth){
        $date = date('Y-m-d', strtotime(" last day of -" . $i . " month", $time));
    }else{
        $date = date('Y-m-d',strtotime(" -" . $i . " month", $time));
    }

    return $date;
}

// 判断是否为手机访问
function sp_is_mobile()
{
    static $sp_is_mobile;

    if(isset($sp_is_mobile)){
        return $sp_is_mobile;
    }

    if(empty($_SERVER['HTTP_USER_AGENT'])){
        $sp_is_mobile = false;
    }elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.)
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
        || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ){
        $sp_is_mobile = true;
    }else{
        $sp_is_mobile = false;
    }

    return $sp_is_mobile;
}

// 文件上传
function fileUp($file, $path)
{
    $name = \think\facade\Filesystem::disk('public')->putFile($path, $file);
    $filePath = str_replace('\\','/',$name);
    return '/storage/'.$filePath;
}

// 打印
function ff($data){
    print_r($data);die;
}

// 写入财务记录
function addFin($user_id = 0, $admin_id = 0, $obj_id = 0, $obj_type = 0, $money_type = 0, $number = 1, $content = ''){
    $finModel = new FinanceRecord();

    $data = [
        'user_id'    => $user_id,
        'admin_id'   => $admin_id,
        'obj_id'     => $obj_id,
        'obj_type'   => $obj_type,
        'money_type' => $money_type,
        'number'     => $number,
        'content'    => $content,
    ];

    $flag = $finModel->add($data);

    if($flag['code'] != 'ok'){
        return [];
    }
    
    return $flag['data'];
}

function getSystemVal()
{
    return Db::name('system')->where('id', 1)->find();
}

/**
 * 模拟get请求
 * @param string $url 请求地址
 * @return array
*/
function curl_get($url)
{
    $headers = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');
    $oCurl = curl_init();

    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }

    curl_setopt($oCurl, CURLOPT_TIMEOUT, 20);
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);

    if (intval($aStatus["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * 模拟post请求
 */
function curl_post($url, $data = array())
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

//HTTP请求（支持HTTP/HTTPS，支持GET/POST）
function curl_post2($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

// 发送验证码
function sendSms($phone, $code){
    $CorpID = "CDJS008664";
    $Pwd = "zm0513@";
    $Mobile = $phone;
    $Content = "您的验证码为". $code ."，该验证码在5分钟之内有效，请勿泄露。【康业科技】";
    $SendTime = "";
    $Sms = 1;
    header("Content-type: text/html; charset=utf-8");
    date_default_timezone_set('PRC'); //设置默认时区为北京时间
    $ContentS = rawurlencode(mb_convert_encoding($Content, "gb2312", "utf-8"));
    $url = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx?";
    $curpost = "CorpID=".$CorpID."&Pwd=".$Pwd."&Mobile=".$Mobile."&Content=".$ContentS."&SendTime=".$SendTime;

    if($Sms == 1){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 -https
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_URL, $url.$curpost);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $result = curl_exec($ch);
        curl_close($ch);
        //$result = file_get_contents($url.$curpost);
    }else if($Sms == 2){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 -https
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curpost);
        $result = curl_exec($ch);
        curl_close($ch);
    }else{
        $result = 0;
    }

    return $result;
}

/**
 * 自动取消付款
 * @param string $data 参数
 * @return 
 */
function removeOrderJob($data)
{
    // 1.当前任务将由哪个类来负责处理。
    // 当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
    $jobHandlerClassName = 'app\job\RemoveOrder';
    
    // 2.当前任务归属的队列名称，如果为新队列，会自动创建
    $jobQueueName = "RemoveOrder";
    
    // 3.当前任务所需的业务数据, 不能为 resource 类型，其他类型最终将转化为json形式的字符串
    // (jobData 为对象时，存储其public属性的键值对 )
    $jobData = $data;
    
    // 4.将该任务推送到消息队列，等待对应的消费者去执行
    // 自动取消时间
    $delay = 5 * 60;

    $isPushed = Queue::later($delay, $jobHandlerClassName, $jobData, $jobQueueName);
    // $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
    
    // database 驱动时，返回值为 1|false；redis 驱动时，返回值为 随机字符串|false
    if( $isPushed !== false ){
        Log::write(date('Y-m-d H:i:s') . " a new RemoveOrder Job is Pushed to the MQ");
    }else{
        Log::write("Oops, something went wrong");
    }
}
